using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
using System.IO;

namespace VASCSiteAction
{
	class Receiver : SPFeatureReceiver
	{
		public override void FeatureActivated(SPFeatureReceiverProperties properties)
		{
			try
			{
				// Tell the web site to use a custom copy of the core.css file.  This
				// will automatically create a copy in the "_style" folder of the
				// web site and point all web site references to the original 
				// file (/_layouts/styles/core.css) to this new file now having the
				// url of "[web]/_styles/core.css" file.
				SPWeb web = (SPWeb)properties.Feature.Parent;
				web.CustomizeCss("core.css");
				web.Update();
				
				try
				{
					// Copy (archive) the original core.css file.
					SPFile coreFile = web.Folders["_styles"].Files["core.css"];
					// Don't replace the archive file if it already exists.
					coreFile.CopyTo("_styles/core-archive-VASC.css", false);
				}
				catch
				{ }

				// Replace the core.css with the custom VASC-core.css file.
				SPFile customFile = web.Folders["_styles"].Files["VASC-core.css"];
				customFile.CopyTo("_styles/core.css", true);
			}
			catch (SPException x)
			{
				logMessage(x.Message, EventLogEntryType.Error);
			}
			catch (Exception x)
			{
				logMessage(x.Message, EventLogEntryType.Error);
			}
		}
		
		public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
		{
			try
			{
				SPWeb web = (SPWeb)properties.Feature.Parent;
				string filename = "core.css";
				web.RevertCss(filename);
				web.Update();
			}
			catch (SPException x)
			{
				logMessage(x.Message, EventLogEntryType.Error);
			}
			catch (Exception x)
			{
				logMessage(x.Message, EventLogEntryType.Error);
			}
		}
		
		public override void FeatureInstalled(SPFeatureReceiverProperties properties)
		{
			logMessage("View All Site Content (VASC) Site Action feature installed", EventLogEntryType.SuccessAudit);
		}

		public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
		{
			logMessage("View All Site Content (VASC) Site Action uninstalling", EventLogEntryType.Information);
		}

		private void logMessage(string message, EventLogEntryType type)
		{
			if (!EventLog.SourceExists("SharePoint"))
				EventLog.CreateEventSource("SharePoint", "Application");
			EventLog.WriteEntry("SharePoint", message, type);
		}
	}
}